const http = require("http");
const fs = require("fs").promises;
const path = require("path");
const url = require("url");
const os = require("os");
const { createReadStream, createWriteStream } = require("fs");

const mime = require("mime"); // 获取文件类型
const chalk = require("chalk");
const ejs = require('ejs')

const networks = os.networkInterfaces();
const ip = Object.values(networks)
  .reduce((a, b) => a.concat(b), [])
  .filter((item) => item.family === "IPv4" && !item.internal)[0].address;

class Server {
  constructor(options) {
    this.port = options.port || 3000;
    this.driectory = options.directory || process.cwd();
  }

  async handleRequest(req, res) {
    const { pathname } = url.parse(req.url);

    const filePath = path.join(this.driectory, pathname);

    try {
      const statObj = await fs.stat(filePath);
      if (statObj.isFile()) {
        this.sendFile(filePath, req, res);
      } else {
        const dirs = await fs.readdir(filePath);
        const template = path.resolve(__dirname, "template.ejs");
        const p = dirs.map(dir => ({
          dir,
          href: path.join(pathname, dir)
        }));
        const htmlStr = await ejs.renderFile(template, { paths: p });
        res.end(htmlStr);
      }
    } catch (error) {
      console.log(error)
      console.log(chalk.red("读取文件出错"))
    }
  }

  sendFile(filePath, req, res) {
    res.setHeader("Content-Type", mime.getType(filePath) + ";charset=utf-8");
    createReadStream(filePath).pipe(res);
  }

  start() {
    const server = http.createServer(this.handleRequest.bind(this));

    server.listen(this.port, () => {
      console.log(`Server is running at
      http://${ip}:${chalk.green(this.port)}
      http://127.0.0.1:${chalk.green(this.port)}
      `);
      console.log(`Server directory is ${chalk.yellow(this.driectory)} `);
    });
  }
}

module.exports = Server;
